<template>
  <a-modal
    destroyOnClose
    :visible="visible"
    :title="title"
    @update:visible="update"
    @ok="ok"
  >
    <Form ref="formRef" v-model:form="form" :formList="formList" :btnConfig="null">
      <template #user_roles>
        <a-select
          v-model:value="form.user_roles"
          style="width: 100%"
          placeholder="请选择角色"
        >
          <a-select-option v-for="item in roleList" :key="item.id" :value="item.id">
            <span>{{ item.name }}</span>
          </a-select-option>
        </a-select>
      </template>
    </Form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, defineProps, toRefs, defineEmits, watch, onMounted } from "vue";
import Form from "@/components/Form";
import { formList } from "./href";
import { userApi } from "@/api/user";
import { roleApi } from "@/api/role";

const emits = defineEmits(["update:visible", "reload"]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  tempData: {
    default: {},
  },
});
const { visible, tempData } = toRefs(props);
const title = ref("提示");
const formRef = ref();
const form = ref({});

const roleList = ref([]);

watch(visible, (e) => {
  if (!e) return;
  const { id } = tempData.value;
  if (e.id) title.value = "修改用户";
  else title.value = "新增用户";
  form.value = tempData.value;
});

onMounted(() => {
  getRoleList();
});

function update(e) {
  emits("update:visible", e);
}
async function ok() {
  await formRef.value.save();
  await userApi.edit(form.value);
  emits("update:visible", false);
  emits("reload");
}

function getRoleList() {
  roleApi.all().then((data) => {
    roleList.value = data;
  });
}
</script>

<style lang="less" scoped></style>
